package cn.xxxy.fourm.Controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.xxxy.fourm.entity.User;
import cn.xxxy.fourm.model.Message;
import cn.xxxy.fourm.service.UserService;
import cn.xxxy.fourm.util.StringUtil;

@Controller
public class LoginController {
	@Autowired
	private UserService userService;
	
	
	@RequestMapping("/toLogin")
	public String toLogin() {
		return "/background/login";
	}
	@PostMapping("/login")
	public String login(String uname,String upass,HttpSession s) {
		if(StringUtil.isEmpty(uname)||StringUtil.isEmpty(upass)) {
			return "redirect:/front/toLogin";
		}else {
			User user=userService.login(uname,upass);
			if(user!=null&&user.getUserRole().getRname().equals("系统管理员")) {
				s.setAttribute("loginUser", user);
				return "redirect:/toHome";
			}else if(user!=null&&user.getUserRole().getRname().equals("管理员")) {
				s.setAttribute("loginUser", user);
				return "redirect:/toHome";
			}else if(user!=null&&user.getUserRole().getRname().equals("用户")) {
				s.setAttribute("loginUser", user);
				return "redirect:/front/toIndex";
			}
			return "redirect:/front/toLogin";
		}
	}
	@RequestMapping("/loginOut")
	public String loginOut(HttpSession s) {
		s.invalidate();
		return "redirect:/front/toLogin";	
	}
	@PostMapping("/editUpass")
	public Message editUpass(String newPass,HttpSession s) {
		Message m=new Message();
		User user=(User) s.getAttribute("loginUser");
		user.setUpass(newPass);
		userService.update(user);
		m.setMsg("恭喜您修改成功");
		m.setSuccess(true);
		return m;		
	}
}
